package com.hanxiaozhang.no3algorithm;

/**
 * 〈一句话功能简述〉<br>
 * 〈十进制与其它进制之间转换〉
 *
 * @author hanxinghua
 * @create 2023/6/13
 * @since 1.0.0
 */
public class No10RadixConvert {


    public static void main(String[] args) {

        System.out.println("验证 String构造函数入参int[]的值是char转换成int的值");
        int[] i = {1, 2, 3};
        char c = (char) i[0];
        System.out.println(c);
        System.out.println(new String(i, 0, 3));

        System.out.println("---- ---- ---- ----");
        String num = "123";
        System.out.println(Integer.parseInt(num, 4));
        System.out.println(xToTenV1(num, 4));
        System.out.println(xToTenV2(num, 4));
        System.out.println(tenTox(27, 4));

    }

    /**
     * 笨办法，从左往右开始
     * Tips：只支持正数
     *
     * @param num
     * @param radix
     * @return
     */
    private static Integer xToTenV1(String num, Integer radix) {
        if (num.length() == 0 || num.charAt(0) == '-') {
            throw new IllegalArgumentException();
        }
        String[] arrays = num.split("");
        int len = arrays.length;
        int result = 0, digit = 0, digitRadix = 1;
        for (int i = 0; i < len; i++) {
            digit = Integer.parseInt(arrays[len - 1 - i]);
            if (i != 0) {
                digitRadix *= radix;
            }
            result += digit * digitRadix;
        }
        return result;
    }


    /**
     * 参照Integer.parseInt(String s,int radix) 方法
     * 核心逻辑：
     * result*=radix;
     * result-=digit;
     * return -result;
     * Tips：只支持正数
     *
     * @param num
     * @param radix
     * @return
     */
    private static Integer xToTenV2(String num, Integer radix) {

        if (num.length() == 0 || num.charAt(0) == '-') {
            throw new IllegalArgumentException();
        }
        String[] arrays = num.split("");
        int len = arrays.length;
        int result = 0, digit = 0;
        for (int i = 0; i < len; i++) {
            digit = Integer.parseInt(arrays[i]);
            result *= radix;
            result -= digit;
        }
        return -result;
    }


    /**
     * Tips：只支持正数
     *
     * @param mun
     * @param radix
     * @return
     */
    public static String tenTox(int mun, int radix) {
        if (mun < 0) {
            throw new IllegalArgumentException();
        }
        StringBuilder sb = new StringBuilder();
        int[] array = new int[33];
        int index = 32;
        // 短除法
        while (mun >= radix) {
            array[index--] = mun % radix;
            mun = mun / radix;
        }
        array[index] = mun;
        for (int i = index; i < 33; i++) {
            sb.append(array[i]);
        }
        return sb.toString();
    }

}
